


var config = require('../config')
var path = require('path')
var express = require('express')
var webpack = require('webpack')
var opn = require('opn')
//var proxyMiddleware = require('http-proxy-middleware')
var devConfig = require('./devConfig')
var proConfig = require('./proConfig')

var routes = require('../routes/index.js');
var fs = require('fs');
var bodyParser = require("body-parser");

// default port where dev server listens for incoming traffic
var port = "1337"
// Define HTTP proxies to your custom API backend
// https://github.com/chimurai/http-proxy-middleware
//var proxyTable = config.dev.proxyTable
var app = express()
var connect = require('connect');
var session = require("express-session")
var cookieParser = require('cookie-parser');
var MongoStore = require('connect-mongo')(session);

//生产环境和开发环境都会执行的方法
exports.common = function () {

    var mongoose = require('mongoose');

    var dblocal = "";
    var dbPort = "27017";
    //  console.log(process.env.NODE_ENV);


    if (global.env == 20) {
        //生产环境
        port = "1334"
        dblocal = "wangli:wangli83@localhost";
        dbPort = "17017";
        app.use("/", express.static('./dist'));
    }
    else {
        //开发环境
        // var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)
        // app.use(staticPath, express.static('./public'))


        port = "1337"
        dblocal = "localhost";
        dbPort = "27017";
        var compiler = webpack(devConfig)

        var devMiddleware = require('webpack-dev-middleware')(compiler, {
            publicPath: devConfig.output.publicPath,
            stats: {
                colors: true,
                chunks: false
            }
        })

        var hotMiddleware = require('webpack-hot-middleware')(compiler)
        // force page reload when html-webpack-plugin template changes
        compiler.plugin('compilation', function (compilation) {
            compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
                hotMiddleware.publish({ action: 'reload' })
                cb()
            })
        })

        // // proxy api requests
        // Object.keys(proxyTable).forEach(function (context) {
        //   var options = proxyTable[context]
        //   if (typeof options === 'string') {
        //     options = { target: options }
        //   }
        //   app.use(proxyMiddleware(context, options))
        // })

        // // handle fallback for HTML5 history API
        // app.use(require('connect-history-api-fallback')())

        // serve webpack bundle output
        app.use(devMiddleware)

        // enable hot-reload and state-preserving
        // compilation error display
        app.use(hotMiddleware)

        // serve pure static assets

    }

    app.use(bodyParser.json());
    var db = mongoose.createConnection(dblocal, "uzor", dbPort);
    db.on('error', console.error.bind(console, 'connection error:'));

    db.on('connected', function () {
        console.log('uzor数据库已经打开!');

    });

    global.dbUzor = db;
    app.use(cookieParser());
    //  app.use(connect.cookieParser())
    app.use(session({
        secret: "wangli",

        cookie: { maxAge: 800000000 },  //设置maxAge是80000ms，即80s后session和相应的cookie失效过期
        resave: false,
        saveUninitialized: true,
        store: new MongoStore({
            url: "mongodb://" + dblocal + ":" + dbPort + "/uzor",
            collection: "sessions"
        })

    }))

    app.use("/public", express.static('./public'));
    app.use("/upload", express.static('./src/upload'));
    app.post('/file', routes.file);
    app.post('/a', routes.ajax);
    app.get('/api', routes.api);
    module.exports = app.listen(port, function (err) {
        if (err) {
            console.log(err)
            return
        }
        var uri = 'http://localhost:' + port
        console.log('Listening at ' + uri + '\n')
        if (global.env == 20) {

        }
        else {
            try {
                opn(uri, { app: ['google chrome', '--incognito'] });
            } catch (e) {

            } finally {

            }


        }

    })





}

